package cn.itsource.ymcc.web.controller;

import cn.itsource.ymcc.domain.CourseDoc;
import cn.itsource.ymcc.query.CourseDocQuery;
import cn.itsource.ymcc.repository.CourseElasticsearchRepository;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ICourseESService;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/es")
public class ESCourseController {
    @Autowired
    private CourseElasticsearchRepository repository;

    @Autowired
    private ICourseESService iCourseESService;

    @PostMapping("/courseInfo")
    public JsonResult courseInfo(@RequestBody List<Long> courseIds){
        Iterable<CourseDoc> courseDocs = repository.findAllById(courseIds);
        return JsonResult.success().setData(courseDocs);
    }

    @PreAuthorize("hasAnyAuthority('yyyy:xxxx')")
    @PostMapping("/save")
    public JsonResult save(@RequestBody List<CourseDoc> courseDoc){
        repository.saveAll(courseDoc);
        return JsonResult.success();
    }

    @DeleteMapping("/delete/{id}")
    public JsonResult delete(@PathVariable("id")Long id){
        repository.deleteById(id);
        return JsonResult.success();
    }

    @PostMapping("/search")
    public JsonResult search(@RequestBody CourseDocQuery courseDocQuery){
        return iCourseESService.search(courseDocQuery);
    }

    @GetMapping("/select/{courseId}")
    public JsonResult selectByCourseId(@PathVariable("courseId")Long courseId){
        Optional<CourseDoc> byId = repository.findById(courseId);
        CourseDoc courseDoc = byId.orElse(new CourseDoc());
        String s = JSON.toJSONString(courseDoc);
        return JsonResult.success().setData(s);
    }

    @PostMapping("/selectByCourseIds")
    public JsonResult selectByCourseIds(@RequestBody List<Long> ids){
        Iterable<CourseDoc> allById = repository.findAllById(ids);
        ArrayList<CourseDoc> courseDocs = Lists.newArrayList(allById);
        if(courseDocs.isEmpty()){
            return JsonResult.error("数据获取失败");
        }
        return JsonResult.success().setData(JSON.toJSONString(courseDocs));
    }


}
